'use strict'

class manage {
    constructor () {

    }
    // __mid(){// 启用token-verify中间件
    //     return [
    //       {
    //         name:'token-verify',
    //         path:['list','get','post','delete']
    //       }
    //     ]
    // }
    async list(c) { //  活动列表展示路由
        let sqltext = `SELECT * FROM activity ORDER BY "activityId" DESC`
        try {
            let r = await c.service.psql.query(sqltext,[]);
            c.send(JSON.stringify(r.rows))
            
        } catch (err) {
            c.status(500).send("Database's operations failed!")
        }
    }
    async get(c) { //单个活动展示路由
        let sqltext = `SELECT * FROM activity WHERE "activityId"=$1`
        try {
            let r = await c.service.psql.query(sqltext,[c.param.id]);
            if (r.rowCount != 0) { 
                c.send(JSON.stringify(r.rows))
            } else {
                c.status(500).send('Show activity failed!')
            }
        } catch (err) {
            c.status(500).send("Database's operations failed!")
        }
    }
    async post(c) { //活动更新/添加路由
        console.log('执行了post manage');
        // 此处应写一个判断，即如果有图片则需要去保存图片且保存图片路径
        let isUpdate = c.headers.update;
        console.log("isUpdate",isUpdate);
        if (isUpdate == 'true') { //更新活动
            console.log("执行了更新活动--------------")
            try {
                const fs = require('fs');
                let firstsqltext = `SELECT "activityImg" FROM activity WHERE "activityId"=$1`;
                let data = JSON.parse(c.body.toString());
                let firstR = await c.service.psql.query(firstsqltext,[data.activityId]);
                console.log(data);
                console.log(firstR);
                if (firstR.rowCount != 0) {
                    if (firstR.rows[0].activityImg !== null) {//原来有图，只需要更新图片并删除老图片
                        let picName = firstR.rows[0].activityImg;
                        fs.unlinkSync(`/home/imgs/${picName}`);
                        let sqltext = `UPDATE activity SET "shortTitle"=$1,`
                                +`"activityImg"=$2,"shopContent"=$3 WHERE "activityId"=$4`;
                        // let startTime = data.activityTime[0].split('T')[0].split('-');
                        // let endTime = data.activityTime[1].split('T')[0].split('-');
                        // for (let j = 0; j < 3; j++) {
                        //     if (j == 0) {
                        //         startTime[j] = startTime[j] + '年';
                        //         endTime[j] = endTime[j] + '年'
                        //     }
                        //     else if (j == 1) {
                        //         startTime[j] = startTime[j] + '月';
                        //         endTime[j] = endTime[j] + '月'
                        //     }
                        //     else{
                        //         startTime[j] = startTime[j] + '日';
                        //         endTime[j] = endTime[j] + '日'
                        //     } 
                        // }
                        // startTime = startTime.join("");
                        // endTime = endTime.join("");
                        // let timeStr = startTime+"到"+endTime;
                        // console.log("timeStr：",timeStr)
                        let r = await c.service.psql.query(sqltext,[data.shortTitle,data.activityImg,data.shopContent,data.activityId]);
                        console.log('标志2')
                        console.log(r);
                        if (r.rowCount != 0) { 
                            c.send('Update activity successfully!')
                        } else {
                            c.status(500).send('Update activity failed!')
                        }
                    }
                    else{//原来没图，需要新加图片
                        let sqltext = `UPDATE activity SET "shortTitle"=$1,`
                                +`"activityImg"=$2,"shopContent"=$3 WHERE "activityId"=$4`;
                        let r = await c.service.psql.query(sqltext,[data.shortTitle,data.activityImg,data.shopContent,data.activityId]);
                        console.log('标志2')
                        console.log(r);
                        if (r.rowCount != 0) { 
                            c.send('Update activity successfully!')
                        } else {
                            c.status(500).send('Update activity failed!')
                        }
                    }
                } else {
                    c.status(500).send('Update activity failed!')
                }
                
            } catch (err) {
                c.status(500).send("Database's operations failed!")
            }
        }
        else{ // 添加活动
            
            try {
                console.log("执行了添加活动--------------")
                let data = JSON.parse(c.body.toString());
                console.log(data);
                let sqltext = `INSERT INTO activity("shortTitle","activityImg","shopContent")`  // 此处应写一个判断，即如果有图片则需要去保存图片且保存图片路径
                            +` VALUES($1,$2,$3)`;
                // let startTime = data.activityTime[0].split('T')[0].split('-');
                // let endTime = data.activityTime[1].split('T')[0].split('-');
                // for (let j = 0; j < 3; j++) {
                //     if (j == 0) {
                //         startTime[j] = startTime[j] + '年';
                //         endTime[j] = endTime[j] + '年'
                //     }
                //     else if (j == 1) {
                //         startTime[j] = startTime[j] + '月';
                //         endTime[j] = endTime[j] + '月'
                //     }
                //     else{
                //         startTime[j] = startTime[j] + '日';
                //         endTime[j] = endTime[j] + '日'
                //     } 
                // }
                // startTime = startTime.join("");
                // endTime = endTime.join("");
                // let timeStr = startTime+"到"+endTime;
                // console.log("timeStr：",timeStr)
                let r = await c.service.psql.query(sqltext,[data.shortTitle,data.activityImg,data.shopContent]);
                console.log('标志2')
                console.log(r)
                if (r.rowCount != 0) { 
                    c.send('Add activity successfully!')
                } else {
                    c.status(500).send('Add activity failed!')
                }
            } catch (err) {
                c.status(500).send("Database's operations failed!")
            }
        
        }

        
    }
    async delete(c) { //活动删除路由
        const fs = require('fs');
        let firstsqltext = `SELECT "activityImg" FROM activity WHERE "activityId"=$1`;
        
        try {
            let firstR = await c.service.psql.query(firstsqltext,[c.param.id]);
            console.log(firstR)
            if (firstR.rows[0].activityImg != null) {
                let picName = firstR.rows[0].activityImg;
                fs.unlinkSync(`/home/imgs/${picName}`);
                let sqltext = `DELETE FROM activity WHERE "activityId"=$1`
                let r = await c.service.psql.query(sqltext,[c.param.id]);
                if (r.rowCount != 0) { 
                    c.send(JSON.stringify('Delete activity successfully!'))
                } else {
                    c.status(500).send('Delete activity failed!')
                }
            
            } else {
                let sqltext = `DELETE FROM activity WHERE "activityId"=$1`
                let r = await c.service.psql.query(sqltext,[c.param.id]);
                if (r.rowCount != 0) { 
                    c.send(JSON.stringify('Delete activity successfully!'))
                } else {
                    c.status(500).send('Delete activity failed!')
                }
            }
        } catch (err) {
            c.status(500).send("Database's operations failed!")
        }
        // let sqltext = `DELETE FROM activity WHERE "activityId"=$1`
        // try {
        //     let r = await c.service.psql.query(sqltext,[c.param.id]);
        //     if (r.rowCount != 0) { 
        //         c.send(JSON.stringify('Delete activity successfully!'))
        //     } else {
        //         c.status(500).send('Delete activity failed!')
        //     }
        // } catch (err) {
        //     c.status(500).send("Database's operations failed!")
        // }
    }

}
module.exports = manage;